﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIT.Controls.Input;

namespace UIT.Controls.Containers
{
    public class ControlFinder : IControlFinder
    {
        private bool stopSearch;
        private IControl root;
        private string id;

        public ControlFinder()
        {
        }

        #region IVisitor<IControl> Members

        public void Visit(IControl visitable)
        {
            CheckCondition(visitable);
            if (stopSearch || visitable == null)
                return;
            if (visitable.IsContainer)
                foreach (IControl item in ((IContainer<IContainer, IControl>)visitable).Children)
                {
                    Visit(item);
                    if (stopSearch)
                        break;
                }

        }

        #endregion

        #region IVisitor<Button> Members

        private void CheckCondition(IControl visitable)
        {
            if (visitable == null)
                return;
            stopSearch = visitable.Id == id;
            if (stopSearch)
                Control = visitable;
        }

        #endregion

        public IControl Control { get; private set; }

        public IControl Find(string Name, IControl controlToSearchFrom)
        {
            this.root = controlToSearchFrom;
            this.id = Name;
            Visit(root);
            return this.Control;
        }
    }
}
